/*
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-02-29 15:14:38
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-02-29 20:15:17
 * @FilePath: \electron-demo\electron\preload.js
 * @Description: electron 预加载脚本
 */
//import { contextBridge } from 'electron'
const { contextBridge, ipcRenderer } = require('electron')

if (!window.versions) {
  //通过 versions 这一全局变量，将 Electron 的 process.versions 对象暴露给渲染器。
  contextBridge.exposeInMainWorld('versions', {
    node: () => process.versions.node,
    chrome: () => process.versions.chrome,
    electron: () => process.versions.electron
    // 除函数之外，我们也可以暴露变量
  })
}

if (!window.ipcRenderer) {
  // 暴露 ipcRenderer 到渲染进程
  contextBridge.exposeInMainWorld('ipcRenderer', {
    send: (channel, data) => {
      ipcRenderer.send(channel, data)
    },
    on: (channel, func) => {
      const subscription = (event, ...args) => func(...args)
      ipcRenderer.on(channel, subscription)

      // 返回一个函数来移除事件监听器
      return () => {
        ipcRenderer.removeListener(channel, subscription)
      }
    },
    once: (channel, func) => {
      ipcRenderer.once(channel, (event, ...args) => func(...args))
    },
    off: (channel, func) => {
      ipcRenderer.removeListener(channel, func)
    }
  })
}

ipcRenderer.on('awaken', (event, params) => {
  console.log(params, 'ipcRenderer')
  window.sessionStorage.setItem('awaken', JSON.stringify(params));
})